﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Sys.Api
{
    /// <summary>
    /// 公共Api基类
    /// </summary>
    public class BaseApi
    {
        /// <summary>
        /// 获取Grid数据
        /// </summary>
        /// <param name="rows">数据总行数</param>
        /// <param name="entities">数据对象</param>
        /// <returns>符合条件的Json结果集</returns>
        public string GetGrid<T>(int count, IQueryable<T> entities)
        {
            Hashtable hash = new Hashtable();

            hash["total"] = count;
            hash["rows"] = entities;

            return JsonHelper.ToJson(hash);
        }

        /// <summary>
        /// 获取Grid数据
        /// </summary>
        /// <param name="rows">数据总行数</param>
        /// <param name="entities">数据对象</param>
        /// <returns>符合条件的Json结果集</returns>
        public string GetGrid<T>(int count, IEnumerable<T> entities)
        {
            Hashtable hash = new Hashtable();

            hash["total"] = count;
            hash["rows"] = entities;

            return JsonHelper.ToJson(hash);
        }

        /// <summary>
        /// 获取自定义字段转换Json表单
        /// </summary>
        /// <param name="objs">要转换的数据</param>
        /// <param name="jms">转换规则</param>
        /// <param name="isall">是否保留其他字段</param>
        /// <returns>结果Json集合</returns>
        public string CustomJson<T>(List<T> objs, List<JsonMap> jms, bool isall)
        {
            return JsonHelper.ToJson(CustomHash(objs, jms, isall));
        }

        /// <summary>
        /// 获取自定义字段转换Hash表单
        /// </summary>
        /// <param name="objs">要转换的数据</param>
        /// <param name="jms">转换规则</param>
        /// <param name="isall">是否保留其他字段</param>
        /// <returns>结果Hashtable集合</returns>
        public List<Hashtable> CustomHash<T>(List<T> objs, List<JsonMap> jms, bool isall)
        {
            List<Hashtable> list = new List<Hashtable>();

            foreach (var obj in objs)
            {
                Type t = obj.GetType();

                Hashtable ht = new Hashtable();

                if (isall)
                {
                    foreach (PropertyInfo pi in t.GetProperties())
                    {
                        ht[pi.Name] = pi.GetValue(obj, null);
                    }
                }

                foreach (JsonMap jm in jms)
                {
                    ht[jm.Related] = t.GetProperty(jm.Exist).GetValue(obj, null);
                }

                list.Add(ht);
            }

            return list;
        }
    }
}
